from django.shortcuts import render, redirect
from app02 import models
from app02.utils.pagination import Pagination
from app02.utils.form import PrettyModelForm


def pretty_list(request):
    """ 靓号列表 """
    # print(request.GET)
    # print(request.GET.urlencode())

    """
    for i in range(50):
        models.prettynum.objects.create(mobile="15836274965",price=26,level=2,status=2)
    """
    # 从页面获取q
    # 没有传获取所以
    data_dict = {}
    search_data = request.GET.get('q', '')

    if search_data:
        data_dict["mobile__contains"] = search_data

    queryset = models.prettynum.objects.filter(**data_dict).order_by("id")

    page_object = Pagination(request, queryset)

    context = {
        "search_data": search_data,
        "pretty_list": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 生成页码
    }

    return render(request, 'pretty_list.html', context)


# --------------- ModelForm实例 新建靓号---------------

def pretty_add(request):
    """ 部门靓号(ModelForm版本)"""
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})

    # 用户POST提交数据，数据校验
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        form.save()
        return redirect('/pretty/list/')
    else:
        # 校验失败(在页面上显示错误信息)
        return render(request, 'pretty_add.html', {"form": form})


def pretty_edit(request, nid):
    """ 修改靓号 """
    # 根据nid,获取数据 [obj,]
    row_object = models.prettynum.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PrettyModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})

    # 保持到数据库
    # models.userinfo.objects.filter(id=nid).update()
    # return redirect("/pretty/list/")
    # 用户POST提交数据，数据校验
    form = PrettyModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    else:
        # 校验失败(在页面上显示错误信息)
        return render(request, 'pretty_edit.html', {"form": form})


def pretty_delete(request, nid):
    """ 删除用户"""
    models.prettynum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")
